package com.cn.wanxi.servlet.front;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cn.wanxi.model.*;
import com.cn.wanxi.service.INewsService;
import com.cn.wanxi.service.INewsTypeService;
import com.cn.wanxi.service.impl.NewsServiceImpl;
import com.cn.wanxi.service.impl.NewsTypeServiceImpl;
import com.cn.wanxi.util.DataEncoding;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/news")
public class NewsServlet extends HttpServlet {
    INewsTypeService newsTypeService = new NewsTypeServiceImpl();
    INewsService newsService = new NewsServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.sendRedirect(DataField.LOCALHOST_PORT+"/html/front/news.html");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        DataEncoding.setJsonContentType(resp);
        DataEncoding.setCharacterEncoding(req,resp);
        List<NewsTypeModel> newsTypeList = newsTypeService.getNewsTypeList();
        String pageNum = req.getParameter("page");
        String newsType = req.getParameter("news_type");
        int page = 1;
        if (!"".equals(pageNum) && pageNum!=null)
            page = Integer.parseInt(pageNum);
        int news_type = 0;
        if (!"".equals(newsType) && newsType!=null)
            news_type = Integer.parseInt(newsType);
        Map<String,Object> map = new HashMap<>();
        map.put("page",(page-1)* DataField.NEWS_SIZE);
        map.put("size",DataField.NEWS_SIZE);
        map.put("news_type",news_type);
        List<NewsModel> newsList = newsService.getNewsList(map);
        long newsCount = newsService.getNewsListCount(map);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("newsTypes",newsTypeList);
        jsonObject.put("news",newsList);
        jsonObject.put("newsCount",newsCount);
        jsonObject = JSON.parseObject(JSON.toJSONString(jsonObject, SerializerFeature.DisableCircularReferenceDetect));
        resp.getWriter().print(jsonObject);
    }
}
